//
//  YWAddNewAssetsInventoryTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/10/25.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAddNewAssetsInventoryTableViewController.h"

#import "YWAssetsInventoryRecordHeadTableViewCell.h"
#import "YWNewAssetInventoryEquipmentTableViewCell.h"
#import "YWWriteNoteCell.h"

#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MBProgressHUD.h"
#import "UIView+Extension.h"
#import "MBProgressHUD.h"
#import "YWConst.h"

#import "YWNewAssetsInventoryHeadModel.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWHandler.h"
#import "YWEquipmentManager.h"
#import "YWBuildingManager.h"
#import "YWEquipment.h"
#import "YWAssetCheckRecordDetails.h"
#import "YWAssetCheckRecord.h"
#import "YWLocation.h"
#import "YWBuilding.h"
#import "YWApartment.h"
#import "YWFloor.h"
#import "YWEquipmentType.h"
#import "YWAssetCheckManager.h"
#import "YWCommonTool.h"

@interface YWAddNewAssetsInventoryTableViewController ()<YWWriteNoteCellDelegate>
//设备类型数组
@property (nonatomic, strong) NSMutableArray * equipmentArray;
@property (nonatomic, strong) UIView * footView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) YWNewAssetsInventoryHeadModel * assetModel;
@property (nonatomic, strong) YWAssetCheckRecordDetails * assetCheckDetail;
@property (nonatomic, copy) NSString * note;
@end

@implementation YWAddNewAssetsInventoryTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"清点";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(backToBeforeView:)];
    [self initTableView];
}

- (void)initTableView{
    [self.tableView registerClass:[YWAssetsInventoryRecordHeadTableViewCell class] forCellReuseIdentifier:YWAssetsInventoryRecordHeadTableViewCellIndentifier];
    [self.tableView registerClass:[YWNewAssetInventoryEquipmentTableViewCell class] forCellReuseIdentifier:YWNewAssetInventoryEquipmentTableViewCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 46, 0);
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.tableFooterView = self.footView;
    self.tableView.estimatedRowHeight = 90.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:@"确定" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickCerturnButton:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}

- (NSMutableArray*)equipmentArray{
    if (!_equipmentArray) {
        _equipmentArray = [NSMutableArray array];
        NSInteger locationId = 0;
        if (self.qrCodeId) {
            locationId = [[YWEquipmentManager shareManager]locationIdWithQrcodeId:self.qrCodeId];
        }else if (_locationId){
            locationId = _locationId;
        }
        NSMutableArray * equipmentInfoArray = [NSMutableArray array];
        [equipmentInfoArray addObjectsFromArray:[[YWEquipmentManager shareManager] equipmentTypeArrayWithLocationId:locationId AndEquipmentTypeId:0]];
        [equipmentInfoArray enumerateObjectsUsingBlock:^(YWQrcodeEquipmentInfo *  _Nonnull equipmentInfo, NSUInteger idx, BOOL * _Nonnull stop) {
            YWAssetCheckRecordDetails * checkDetail = [[YWAssetCheckRecordDetails alloc] init];
            
            checkDetail.equipmentType = [[YWEquipmentManager shareManager] equipmentTypeWithEquipmentTypeId:equipmentInfo.equipmentTypeId];
            checkDetail.referQuantity = equipmentInfo.equipmentCount;
            checkDetail.checkQuantity = equipmentInfo.equipmentCount;
            [_equipmentArray addObject:checkDetail];
        }];
    }
    return _equipmentArray;
}

- (YWNewAssetsInventoryHeadModel*)assetModel{
    if (!_assetModel) {
        _assetModel = [[YWNewAssetsInventoryHeadModel alloc] init];
        //清点人
        YWLoginUser * user = [YWLoginTool loginUser];
        _assetModel.assetsName = user.userName;
        //通过二维码Id获取location，位置
        NSInteger locationId = 0;
        if (self.qrCodeId) {
            locationId = [[YWEquipmentManager shareManager]locationIdWithQrcodeId:self.qrCodeId];
        }else if (_locationId){
            locationId = _locationId;
        }
        _assetModel.location = [[YWBuildingManager shareManager] areaLocationWithLocationId:locationId];
        //时间
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm yyyy-MM-dd"];
        _assetModel.createTime = [dateFormatter stringFromDate:[NSDate date]];
    }
    return _assetModel;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section ==1 ? [self.equipmentArray count] : 1 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWAssetsInventoryRecordHeadTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWAssetsInventoryRecordHeadTableViewCellIndentifier];
        [self configureAssetsInventoryListCell:cell atIndexPath:indexPath];
        return cell;
    }else if (indexPath.section == 1){
        YWNewAssetInventoryEquipmentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNewAssetInventoryEquipmentTableViewCellIdentifier];
        [self configureNewAssetsEquipmentListCell:cell atIndexPath:indexPath];
        return cell;
    }else{
        YWWriteNoteCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.delegate = self;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section==0) {
//        return [tableView fd_heightForCellWithIdentifier:YWAssetsInventoryRecordHeadTableViewCellIndentifier cacheByIndexPath:indexPath configuration:^(YWAssetsInventoryRecordHeadTableViewCell *cell) {
//            [self configureAssetsInventoryListCell:cell atIndexPath:indexPath];
//        }];
//    }else if (indexPath.section == 1){
//        return [tableView fd_heightForCellWithIdentifier:YWNewAssetInventoryEquipmentTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWNewAssetInventoryEquipmentTableViewCell *cell) {
//            [self configureNewAssetsEquipmentListCell:cell atIndexPath:indexPath];
//        }];
//    }
    if (indexPath.section == 0 || indexPath.section == 1) {
        return UITableViewAutomaticDimension;
    }else{
        return 90;
    }
}

- (void)configureAssetsInventoryListCell:(YWAssetsInventoryRecordHeadTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    //传对象进去
    cell.assetInventoryModel = self.assetModel;
}

- (void)configureNewAssetsEquipmentListCell:(YWNewAssetInventoryEquipmentTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    //传对象进去
    cell.checkDetail = self.equipmentArray[indexPath.row];
}

#pragma mark - table view section header view

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWAddNewAssetsInventoryTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2016;
        label.numberOfLines = 0;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 25);
    return headerView;
    
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        return @"设备清单";
    }else if (section == 2){
        return @"备注";
    }else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }else{
        return 25;
    }
}

#pragma mark - YWNewAssetInventoryEquipmentTableViewCellDelegate

//- (void)assetCheckTextFieldString:(NSInteger)textFieldCount{
//    self.textFieldCount = textFieldCount;
//    [self.tableView reloadData];
//}

#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString*)note{
    self.note = note;
}

- (void)clickCerturnButton:(id)sender{
    //判断清点记录的数量是否异常
    __block BOOL normal = YES;
    [_equipmentArray enumerateObjectsUsingBlock:^(YWAssetCheckRecordDetails *  _Nonnull recordDetail, NSUInteger idx, BOOL * _Nonnull stop) {
        if (recordDetail.referQuantity != recordDetail.checkQuantity) {
            normal = NO;
            *stop = YES;
        }
    }];
    
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:normal == YES?@"您确认要提交本次清点记录吗？":@"本次清点设备数量异常\n请在备注中注明具体异常情况\n您确认要提交本次清点记录吗？" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    [alertController addAction:[UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"提交" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self postAssetCheckRecord];
    }]];
}

- (void)postAssetCheckRecord{
    if ([YWCommonTool isContainsEmoji:self.note]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    //构建数据
    YWAssetCheckRecord * checkRecord = [[YWAssetCheckRecord alloc] init];
    NSInteger locationId = 0;
    if (self.qrCodeId) {
        locationId = [[YWEquipmentManager shareManager]locationIdWithQrcodeId:self.qrCodeId];
    }else if (_locationId){
        locationId = _locationId;
    }
    checkRecord.building = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
    checkRecord.location = [[YWBuildingManager shareManager] locationWithId:locationId];
    checkRecord.floor = [[YWBuildingManager shareManager] floorWithId:checkRecord.location.floorId];
    checkRecord.apartment = [[YWBuildingManager shareManager] apartmentWithId:checkRecord.floor.apartmentId];
    checkRecord.note = self.note;
    checkRecord.creator.uniqueId = [YWLoginTool loginUser].uniqueId;
    
    [self.HUD show:YES];
    [[YWAssetCheckManager shareManager] postAssetCheckRecordWithCheckRecord:checkRecord recordDetails:_equipmentArray WithComplete:^(BOOL success){
        [self.HUD hide:YES];
        if (success) {
            [YWCommonTool showTextHUDWithContent:@"提交清点记录成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshAssetCheckRecordList object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (void)backToBeforeView:(id)sender{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"退出清点" message:@"您确定退出此次清点吗？" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
